import { ref, watch } from 'vue'
import { defineStore } from 'pinia'
import type { IRouter } from '@/apis/types/user'
import type { Router, RouteRecordRaw } from 'vue-router'

export const useUserStore = defineStore('user', () => {
  const token = ref<string>('')
  const menuList = ref<IRouter[]>([])
  const routerList = ref<(() => void)[]>([])
  const tags = ref<IRouter[]>([])
  const setToken = (newToken: string, menus: IRouter[]) => {
    token.value = newToken
    menuList.value = menus
    tags.value = [{ path: '/home', name: 'home', label: '首页', icon: 'home' }]
  }
  watch(
    [token, menuList, tags],
    (newVal) => {
      localStorage.setItem('userState', JSON.stringify(newVal))
    },
    { deep: true }
  )
  // 退出登录
  const removeToken = () => {
    localStorage.removeItem('userState')
    routerList.value.forEach((item) => {
      if (item) item()
    })
  }
  // 动态路由
  const addMenu = (router: Router, type = 'other') => {
    if (type === 'refresh') {
      ;[token.value, menuList.value, tags.value] = JSON.parse(localStorage.getItem('userState') || '[]')
    }
    const module = import.meta.glob('../../views/**/*.vue')
    const routeArr: IRouter[] = []
    if (!menuList.value) return
    menuList.value.forEach((item) => {
      if (item.children) {
        item.children.forEach((child) => {
          const url = `../../views${item.path}/${child.url}.vue`
          child.component = module[url]
          routeArr.push(...item.children!)
        })
      } else {
        const url = `../../views/${item.url}.vue`
        item.component = module[url]

        routeArr.push(item)
      }
    })

    // 动态路由
    // routerList.value = []
    routeArr.forEach((item) => {
      routerList.value.push(router.addRoute('main', item as RouteRecordRaw)) // main 为主路由
    })
    // console.log(routerList.value)
    // admin登录后 直接user登录，菜单权限未重置继承问题，目前版本无问题
    // 有问题需要 router.removeRoute(item.name)
    // console.log(router.getRoutes())
  }

  // tags

  const currentMenu = ref<IRouter | null>(null)
  const selectMenu = (val: IRouter) => {
    if (val.name === 'home') {
      currentMenu.value = null
    } else {
      currentMenu.value = val
      const index = tags.value.findIndex((item) => item.name === val.name)
      index === -1 ? tags.value.push(val) : ''
    }
  }
  // 点关闭 更新tags
  const updateTags = (tag: IRouter) => {
    const index = tags.value.findIndex((item) => item.name === tag.name)
    tags.value.splice(index, 1)
  }

  return { token, tags, menuList, currentMenu, setToken, removeToken, selectMenu, updateTags, addMenu }
})
